package com.atguigu.mapreduce.reducejoin;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;

public class TableReducer extends Reducer<Text, TableBean, TableBean, NullWritable> {
    @Override
    protected void reduce(Text key, Iterable<TableBean> values, Context context) throws IOException, InterruptedException {
/* 传进来的数据
        01  1001	1   order
        01  1004	4   order
        01  小米          pd
*/
        // 准备两个集合分别装来自不同表的数据
        ArrayList<TableBean> orderBeens = new ArrayList<>();
        TableBean pdBeen = new TableBean();

        // 循环遍历
        for (TableBean value : values) {

            if ("order".equals(value.getFlag())) {
                // 订单表  order

                // 可能有多行的数据,先创建一个临时TableBean对象接收value
                TableBean tmpOrderBeen = new TableBean();
                try {
                    BeanUtils.copyProperties(tmpOrderBeen, value);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }

                orderBeens.add(tmpOrderBeen);
            } else {
                // 商品表  pd

                // 只有一行，直接copy
                try {
                    BeanUtils.copyProperties(pdBeen, value);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }

        // 循环遍历orderBeens，赋值pdname
        for (TableBean orderBeen : orderBeens) {

            orderBeen.setPname(pdBeen.getPname());

            //写出修改后的orderBean对象
            context.write(orderBeen, NullWritable.get());

        }

    }
}
